package com.butterfly.mvc.servlet;

import com.butterfly.mvc.form.ActionForm;
import com.butterfly.mvc.util.MvcParser;
import com.butterfly.mvc.util.Param2Bean;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by DouDou on 2016/9/19.
 */
public class DispatchServlet extends javax.servlet.http.HttpServlet {
    public static final String REDIRECT = "redirect:";

    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        this.doGet(request,response);
    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

        Map<String,ActionBean> mvc = (Map<String,ActionBean>)request.getServletContext().getAttribute("mvc");
        System.out.println(request.getServletPath().split("\\.")[0]);

        ActionBean actionBean = mvc.get(Param2Bean.getPath(request));
        Object[] params = Param2Bean.packageParam(request,response,actionBean.getParams());

        String url = "";
        try{
            Class clazz = Class.forName(actionBean.getClassPath());
            //(Action) action = (Action) clazz.newInstance();
            //如果没有指定方法名，默认使用execute方法
            String methodName = actionBean.getMethod();
            if(methodName == null || methodName.length() == 0) {
                methodName = "execute";
            }
            Method method = clazz.getMethod(methodName, actionBean.getParams());
            url = (String) method.invoke(clazz.newInstance(),params);
            //url = action.execute(formBean,request,response);
        }catch (Exception e){
            e.printStackTrace();
        }

        Map<String,String> config = (Map<String,String>)request.getServletContext().getAttribute("config");
        if(url.startsWith(DispatchServlet.REDIRECT)){
            url = url.replaceFirst(REDIRECT,"").trim();
            response.sendRedirect("/"+url);
        }else{
            RequestDispatcher dis = request.getRequestDispatcher("/"+config.get("pagePrefix")+url+config.get("pageSuffix"));
            System.out.println("/"+config.get("pagePrefix")+url+config.get("pageSuffix"));
            dis.forward(request,response);
        }

    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        ServletContext context = this.getServletContext();
        String param = context.getInitParameter("mvc-config");
        String realPath = context.getRealPath("\\");
        String configXmlPath = realPath + "\\WEB-INF\\classes\\" + param;
        System.out.println(configXmlPath);
        try {
            Map<String, String> configMap = MvcParser.parseXml(configXmlPath);
            context.setAttribute("config",configMap);
            Map<String,ActionBean> serviceMap = new HashMap<String, ActionBean>();
            PackageScan.scan(configMap.get("scanPath"),serviceMap);
            context.setAttribute("mvc",serviceMap);
            System.out.println("初始化系统成功");
        }catch (Exception e){
            System.out.println("初始化系统失败");
            e.printStackTrace();
        }

    }
}
